package com.xhtt.modules.photo.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhtt.common.exception.RRException;
import com.xhtt.common.exception.RRExceptionEnum;
import com.xhtt.common.utils.DateUtils;
import com.xhtt.common.utils.ExportExcel;
import com.xhtt.common.utils.PageUtils;
import com.xhtt.common.utils.Query;
import com.xhtt.modules.msg.entity.MsgInfo;
import com.xhtt.modules.msg.service.MsgUserService;
import com.xhtt.modules.photo.dao.PhotoStagePhotoMapper;
import com.xhtt.modules.photo.entity.PhotoProblem;
import com.xhtt.modules.photo.entity.PhotoRepairs;
import com.xhtt.modules.photo.entity.PhotoStagePhoto;
import com.xhtt.modules.photo.service.IPhotoStagePhotoService;
import com.xhtt.modules.sys.entity.SysUserDeptEntity;
import com.xhtt.modules.sys.entity.SysUserEntity;
import com.xhtt.modules.sys.service.SysDeptService;
import com.xhtt.modules.sys.service.SysUserDeptService;
import com.xhtt.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 现场拍照装车台拍照 服务实现类
 * </p>
 *
 * @author xj
 * @since 2019-02-14
 */
@Service
public class PhotoStagePhotoServiceImpl extends ServiceImpl<PhotoStagePhotoMapper, PhotoStagePhoto> implements IPhotoStagePhotoService {

    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    private MsgUserService msgUserService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserDeptService sysUserDeptService;

    @Autowired
    private SysDeptService sysDeptService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        LocalDateTime startDate = null;
        LocalDateTime endDate = null;
        if (Optional.ofNullable(params.get("createTime")).isPresent()) {

            LocalDateTime createTime = DateUtils.string2LocalDateTime((String) params.get("createTime"), "yyyy-MM-dd 00:00:00");
            startDate = createTime;
            endDate = createTime.plusDays(1);
        }

        // app端一天的数据
        LocalDateTime onceStart = null;
        LocalDateTime onceEnd = null;
        if (Optional.ofNullable(params.get("datetime")).isPresent()) {

            onceStart = DateUtils.string2LocalDateTime((String) params.get("datetime"), "yyyy-MM-dd 00:00:00");
            onceEnd = onceStart.plusDays(1);
        }

        Page<PhotoStagePhoto> page = new Query<PhotoStagePhoto>(params).getPage();

        IPage<PhotoStagePhoto> iPage = baseMapper
                .selectPage(page, new LambdaQueryWrapper<PhotoStagePhoto>()
                        .like(Optional.ofNullable(params.get("customerName")).isPresent(), PhotoStagePhoto::getCustomerName, params.get("customerName"))
                        .like(Optional.ofNullable(params.get("productName")).isPresent(), PhotoStagePhoto::getProductName, params.get("productName"))
                        .like(Optional.ofNullable(params.get("stageName")).isPresent(), PhotoStagePhoto::getStageName, params.get("stageName"))
                        .like(Optional.ofNullable(params.get("createUserName")).isPresent(), PhotoStagePhoto::getCreateUserName, params.get("createUserName"))
                        .in(Optional.ofNullable(params.get("userIds")).isPresent(), PhotoStagePhoto::getCreateUserId, (List<Integer>) params.get("userIds"))
                        .ge(Optional.ofNullable(params.get("createTime")).isPresent(), PhotoStagePhoto::getCreateTime, startDate)
                        .lt(Optional.ofNullable(params.get("createTime")).isPresent(), PhotoStagePhoto::getCreateTime, endDate)
                        .ge(onceStart != null, PhotoStagePhoto::getCreateTime, onceStart)
                        .lt(onceEnd != null, PhotoStagePhoto::getCreateTime, onceEnd)
                        .orderByDesc(PhotoStagePhoto::getCreateTime));

        return new PageUtils(iPage);
    }

    @Override
    public void addMsg(Object obj, SysUserEntity user) {
        Integer userId = user.getUserId().intValue();
        MsgInfo msgInfo = null;
        if (obj instanceof PhotoStagePhoto) {
            msgInfo = new MsgInfo("现场拍照", "装车台拍照", "装车台拍照", JSON.toJSONString(obj));
        } else if (obj instanceof PhotoProblem) {
            msgInfo = new MsgInfo("现场拍照", "问题记录", "问题记录", JSON.toJSONString(obj));
        } else if (obj instanceof PhotoRepairs) {
            msgInfo = new MsgInfo("现场拍照", "报修记录", "报修记录", JSON.toJSONString(obj));
        }
        MsgInfo finalMsgInfo = msgInfo;
        taskExecutor.submit(() -> {
            SysUserEntity teamLeader = sysUserService.getTeamLeaderByUser(userId);
            Set<Integer> userIds = new HashSet<>();
            userIds.add(userId);
            // 存在就推送给组长，不存在则推送给部门管理员
            if (teamLeader != null) {
                if (!userId.equals(teamLeader.getUserId().intValue())) {
                    userIds.add(teamLeader.getUserId().intValue());
                }
            } else {
                List<SysUserEntity> deptLeaderList = sysUserService.getDeptLeaderByDept(
                        sysUserDeptService.getOne(new LambdaQueryWrapper<SysUserDeptEntity>()
                                .eq(SysUserDeptEntity::getUserId, userId))
                                .getDeptId().intValue());
                userIds.addAll(deptLeaderList.stream().map(u -> u.getUserId().intValue()).collect(Collectors.toList()));
            }
            msgUserService.insertBatch(finalMsgInfo, new ArrayList<>(userIds));
        });
    }

    @Override
    public void exportExcel(HttpServletResponse response, Map<String, Object> params) {

        ExportExcel exportExcel = new ExportExcel();

        params.put("limit", "65000");

        PageUtils pageUtils = queryPage(params);
        List list = pageUtils.getList();
        String fileName = "装车台拍照记录";
        String sheetName = "sheet1";
        String[] headers = {"客户名称", "产品名称", "装车台号", "装车罐号", "装车车号", "记录人员", "装车台拍照时间"};
        String[] columns = {"customerName", "productName", "stageName", "potNo", "carNo", "createUserName", "createTimeStr"};
        try {
            exportExcel.exportExcel(fileName, sheetName, headers, columns, list, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException(RRExceptionEnum.EXPORT_FAIL);
        }
    }
}
